package com.sense.common.lang;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sense.common.lang.annotation.JsonResponse;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;
import java.util.Objects;

@ControllerAdvice
public class JsonResponseHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
        Method method = methodParameter.getMethod();
        Class<?> clazz = Objects.requireNonNull(method, "method is null").getDeclaringClass();
        // 看看类上有没有JsonResponse
        JsonResponse annotation = clazz.getAnnotation(JsonResponse.class);
        // 看看方法上是否有注解
        JsonResponse methodAnnotation = method.getAnnotation(JsonResponse.class);
        if (methodAnnotation != null) {
            annotation = methodAnnotation;
        }
        if (method.getAnnotatedReturnType().getType().getTypeName().equalsIgnoreCase(FileSystemResource.class.getName())) {
            return false;
        }
        return annotation != null && !annotation.ignore();
    }


    @Override
    @SneakyThrows
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aclazz, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof String && !MediaType.APPLICATION_XML_VALUE.equals(mediaType.toString())) {
            ObjectMapper om = new ObjectMapper();
            response.getHeaders().set("Content-Type", "application/json");
            RestfulResponse restfulResponse = RestfulResponse.of(body);
            return om.writeValueAsString(restfulResponse);
        }
        if (Objects.isNull(body) && MediaType.TEXT_HTML_VALUE.equals(mediaType.toString())) {
            ObjectMapper om = new ObjectMapper();
            response.getHeaders().set("Content-Type", "application/json");
            RestfulResponse restfulResponse = RestfulResponse.of(null);
            return om.writeValueAsString(restfulResponse);
        }
        return RestfulResponse.of(body);
    }
}